#include "InputManager.h"

// Initialize the Input Manager
void cInputManager::Init(const tActionMapping laActionMapping[], unsigned int luiActionCount) {
	// Initializing the devices
	cGenericDevice * lpKeyboard = new cKeyboard;
	lpKeyboard->Init();
	// This needs to match with the enum eDevices
	// eKeyboard = 0 -> Keyboard in the index 0 of the vector
	mDevices.push_back(lpKeyboard);
	// Initializing the actions vector
	mActions.resize( luiActionCount);
	// Initializing the mapping structure
	mMapped.resize( luiActionCount);

	int register liIndex = 0;
	while ( laActionMapping[ liIndex].miAction >= 0) {
		cInputEntry lEntry;
		lEntry.muiDevice = laActionMapping[ liIndex].miDevice;
		lEntry.muiChannel = laActionMapping[ liIndex].miChannel;
		mMapped[ laActionMapping[ liIndex].miAction ].push_back(lEntry);
		liIndex++;
	}
}
	
// Update the Input Manager
void cInputManager::Update(const float &lfTimeStep) {
	// Update the devices
	int liSize = mDevices.size();

	for (int register liDeviceId = 0; liDeviceId < liSize; liDeviceId++) {
		if (mDevices[liDeviceId] != NULL)
			mDevices[liDeviceId]->Update();
	}

	// For each action
	liSize = mMapped.size();
	for (int liActionId = 0; liActionId < liSize; liActionId++) {
		// For each map
		int liMapSize = mMapped[liActionId].size();
		float lfValue = 0.0f;

		for (int liMapId = 0; liMapId < liMapSize; liMapId++) {
			// Calculate the value of the input
			const cInputEntry& lEntry = mMapped[liActionId][liMapId];
			lfValue += Check(lEntry.muiDevice, lEntry.muiChannel);
		}
		// Set the value in the action
		mActions[liActionId].Update(lfTimeStep, lfValue);
	}
}
	
// Check the channel of a device
float cInputManager::Check(int liDevice, int liChannel) {
	if (mDevices[liDevice] != NULL && mDevices[liDevice]->IsValid())
		return (mDevices[liDevice]->Check(liChannel));
	return 0.0f;
}

// Deinitialize the Input Manager
void cInputManager::DeInit() {
	int liSize = mDevices.size();
	for (int register liDeviceIndex = 0; liDeviceIndex < liSize; liDeviceIndex++) {
		mDevices[liDeviceIndex]->DeInit();
		delete(mDevices[liDeviceIndex]);
	}
	mActions.resize(0);
	mMapped.resize(0);
}